package com.sjft.cloud.commons.logger.utils;

import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.HttpUtil;
import com.sjft.cloud.commons.logger.constant.LogTypeEnum;
import com.sjft.cloud.commons.logger.domain.Log;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * LogUtils
 *
 * @author Jin
 */
@UtilityClass
public class LogUtils {

    public static Log buildSysLog(LogTypeEnum logTypeEnum) {
        HttpServletRequest request = ((ServletRequestAttributes) Objects
                .requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

        return Log.builder()
                .createBy(getUsername())
                .type(logTypeEnum.getType())
                .remoteAddr(ServletUtil.getClientIP(request))
                .requestUri(URLUtil.getPath(request.getRequestURI()))
                .method(request.getMethod()).userAgent(request.getHeader("user-agent"))
                .params(HttpUtil.toParams(request.getParameterMap()))
                .clientId(getClientId())
                .build();
    }

    private static String getClientId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof OAuth2Authentication) {
            OAuth2Authentication auth2Authentication = (OAuth2Authentication) authentication;
            return auth2Authentication.getOAuth2Request().getClientId();
        }
        return null;
    }

    private static String getUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return "";
        }
        return authentication.getName();
    }
}
